<template>
  <div class="toolDialog" v-if="isPipelineShow">
    <transition name="el-zoom-in-top">
      <div class="positonBar" v-show="hideBarFromvuex">
        <div class="tool-item" tabindex="0" @click="handleDialog(1)">
          <div class="tool-icon"><i class="iconfont icon-feedback"></i></div>
          <div class="tool-text">爆管分析</div>
        </div>
        <div class="tool-item" tabindex="0" @click="handleDialog(2)">
          <div class="tool-icon"><i class="iconfont icon-legend"></i></div>
          <div class="tool-text">横断面分析</div>
        </div>
        <div class="tool-item" tabindex="0" @click="handleDialog(3)">
          <div class="tool-icon"><i class="iconfont icon-eagleeye"></i></div>
          <div class="tool-text">纵断面分析</div>
        </div>
        <div class="tool-item" tabindex="0" @click="handleDialog(4)">
          <div class="tool-icon"><i class="iconfont icon-eagleeye"></i></div>
          <div class="tool-text">连通分析</div>
        </div>
        <div class="tool-item" tabindex="0" @click="handleDialog(5)">
          <div class="tool-icon"><i class="iconfont icon-eagleeye"></i></div>
          <div class="tool-text">缓冲区分析</div>
        </div>
      </div>
    </transition>
    <PipelineBrust
      v-if="isPipeBrustShow"
      :dialogVisible="isPipeBrustShow"
    ></PipelineBrust>
    <CrossSectional
      v-if="isCrossSectional"
      :dialogVisible="isCrossSectional"
      :tableData="areaTableData"
      :isLoading="isCrossLoading"
    ></CrossSectional>
    <LongitudinalVue
      v-if="isLongitudinal"
      :dialogVisible="isLongitudinal"
      :tableData="areaTableData"
      :isLoading="isCrossLoading"
    ></LongitudinalVue>
    <Connectivity
      v-if="isConnectivity"
      :dialogVisible="isConnectivity"
    ></Connectivity>
    <BufferAnalysis
      v-if="isBuffered"
      :dialogVisible="isBuffered"
    ></BufferAnalysis>
    <!-- <vavleManageForm v-show="showValveOperate"></vavleManageForm> -->
    <!-- <UserEquipConnection
      v-if="isUserEquipShowPop"
      @update:dialogVisible="isUserEquipShow = $event"
    >
    </UserEquipConnection> -->
  </div>
</template>

<script>
import UserEquipConnection from "../EquipmentManagement/components/UserEquipConnection.vue";
// import vavleManageForm from "./component/valveManageForm.vue";
import PipelineBrust from "./component/PipelineBrust.vue";
import CrossSectional from "./component/CrossSectional.vue";
import LongitudinalVue from "./component/Longitudinal.vue";
import Connectivity from "./component/Connectivity.vue";
import BufferAnalysis from "./component/BufferAnalysis.vue";
import dmgis from "@/api/dmgis";
import { markRaw } from "vue";
import LineString from "ol/geom/LineString";
import { Fill, Stroke, Style, Circle } from "ol/style";
import * as turf from "@turf/turf";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { Feature } from "ol";
import { transform, useGeographic, Projection, addProjection } from "ol/proj";
export default {
  name: "OPipelineBar",
  components: {
    PipelineBrust,
    CrossSectional,
    LongitudinalVue,
    Connectivity,
    BufferAnalysis,
    // vavleManageForm,
    UserEquipConnection,
  },
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      keywords: [],
      areaTableData: [],
      map: null,
      projectLayer: null,
      isPipeBrustShow: false,
      isCrossSectional: false,
      isLongitudinal: false,
      isConnectivity: false,
      isBuffered: false,
      hideBar: true,
      queryDataList: [],
      dmPipProjectLayer: null,
      isCrossLoading: false,
    };
  },
  computed: {
    isPipelineShow() {
      // 返回 prop 的值
      return this.dialogVisible;
    },
    showValveOperate() {
      return this.$store.getters.showValveOperate;
    },
    isUserEquipShowPop() {
      return this.$store.state.isUserEquipShow;
    },
    hideBarFromvuex() {
      return this.$store.state.isPipeShow;
    },
    // drawpoints() {
    //   return this.$store.getters.drawpoints;
    // },
  },
  watch: {
    //    async drawpoints(val) {
    //
    //         // 计算外接矩形的坐标
    //         let boundingbox = [
    //             [
    //                 Math.min(val[0][0], val[1][0]),
    //                 Math.min(val[0][1], val[1][1]),
    //             ],
    //             [
    //                 Math.max(val[0][0], val[1][0]),
    //                 Math.max(val[0][1], val[1][1]),
    //             ],
    //         ];
    //         let getFeatureParams = new dmgis.object.FeatureServiceParam(
    //       "TapWaterMap"
    //     );
    //     let that=this;
    //     let SpatialQuery = new dmgis.object.SpatialQuery();
    //     var rect = new dmgis.object.Envelope();
    //     rect.minx = boundingbox[0][0];
    //     rect.miny = boundingbox[0][1];
    //     rect.maxx = boundingbox[1][0];
    //     rect.maxy = boundingbox[1][1];
    //     SpatialQuery.env = rect; //矩形
    //     getFeatureParams.sql = SpatialQuery;
    //     getFeatureParams.strlayername = 'pipeline500_799mm_center';
    //     await that.projectLayer
    //           .SendFeatureMapService(getFeatureParams)
    //           .then(() => {
    //             dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
    //               function (feature) {
    //                 if (feature.objset) {
    //                   that.queryDataList = feature.objset;
    //                   ;
    //                   this.isCrossSectional = !this.isCrossSectional;
    //                 }else{
    //                  this.$message.error('无数据')
    //                 }
    //               };
    //           });
    //       }
  },
  methods: {
    initMap() {
      this.map = this.$store.getters.Map;
      let projection_szbj54 = new Projection({
        code: "sz2000",
        units: "m",
      });
      this.dmPipProjectLayer = new dmgis.olmap.PipLayer(
        "pipeLineNet",
        process.env.VUE_APP_BASE_API + "/dmgis",
        {
          maxZoom: 18,
          minZoom: 0,
          opacity: 1,
          projection: projection_szbj54,
        }
      );

      this.$store.commit("setPipProjectLayer", markRaw(this.dmPipProjectLayer));
      // setTimeout(() => {
      //     this.map = this.$store.getters.Map;
      //     if (this.map) {
      //         ;
      //     } else {
      //         console.error('地图实例未找到');
      //     }
      // }, 1000); // 延迟 1000 毫秒（1秒）后执行
    },
    initLayer() {
      this.projectLayer = this.$store.getters.projectLayer;
    },
    handleDialog(index) {
      this.$store.commit("setisPipeShow", false);
      switch (index) {
        case 1:
          this.isBuffered = false;
          this.isConnectivity = false;
          this.isCrossSectional = false;
          this.isLongitudinal = false;
          this.isPipeBrustShow = !this.isPipeBrustShow;
          break;
        case 2:
          this.crossSectionalAnalysis();
          this.isBuffered = false;
          this.isConnectivity = false;
          this.isPipeBrustShow = false;
          this.isLongitudinal = false;

          break;
        case 3:
          this.verticalSectionalAnalysis();
          this.isBuffered = false;
          this.isConnectivity = false;
          this.isPipeBrustShow = false;

          this.isCrossSectional = false;
          break;
        case 4:
          this.isBuffered = false;
          this.isConnectivity = !this.isConnectivity;
          this.isPipeBrustShow = false;
          this.isLongitudinal = false;
          this.isCrossSectional = false;
          break;
        case 5:
          this.isBuffered = !this.isBuffered;
          this.isConnectivity = false;
          this.isPipeBrustShow = false;
          this.isLongitudinal = false;
          this.isCrossSectional = false;
          break;
        default:
      }
    },
    crossSectionalAnalysis() {
      // if (!this.map.interaction.drawLayer) {
      //     this.map.interaction.initDraw('绘制图层');
      // }
      this.map.interaction.addDraw("LineString", 1, 0);
      this.map.map.on("dblclick", this.getFeatureByLine);
      this.isCrossSectional = true;
    },
    verticalSectionalAnalysis() {
      this.map.interaction.addDraw("LineString", 1, 0);
      this.map.map.on("dblclick", this.getFeatureByLine);
      this.isLongitudinal = true;
    },
    //更改管线名称
    convertLayerNameToFormattedString(layerName) {
  // 使用正则表达式匹配数字和单位（如 500mm）
  const match = layerName.match(/(\d+mm)/);
  if (match) {
    // 提取匹配到的内容（如 500mm）
    const size = match[1];
    // 拼接为新字符串
    return `${size}管线`;
  } else {
    // 如果没有匹配到，返回默认值或原字符串
    return "未知管线";
  }
},
    getFeatureByLine() {
      this.map.map.un("dblclick", this.getFeatureByLine);
      let resultData = [];

      this.isCrossLoading = true;
      let line1 = this.$store.getters.drawpoints;
      //以线绘制成矩形进行空间查询,绘制平行线
      let delta = 10; //数据偏移量
      //计算方向向量
      let dx = line1[1][0] - line1[0][0];
      let dy = line1[1][1] - line1[0][1];
      // 计算单位方向向量
      let length = Math.sqrt(dx * dx + dy * dy);
      let ux = dx / length;
      let uy = dy / length;
      // 计算垂直方向向量（即平行线的方向）
      let vx = -uy;
      let vy = ux;
      // 生成平行线的两个端点
      let p1x = line1[0][0] + vx * delta;
      let p1y = line1[0][1] + vy * delta;
      let p2x = line1[1][0] + vx * delta;
      let p2y = line1[1][1] + vy * delta;
      // 平行线
      let line2 = [
        [p1x, p1y],
        [p2x, p2y],
      ];
      let areaData = [...line1, ...line2, line1[0]];
      let getFeatureParams = new dmgis.object.FeatureServiceParam(
        "TapWaterMap"
      );
      let SpatialQuery = new dmgis.object.SpatialQuery();
      let areaPos = "";
      areaData.forEach((item, index) => {
        let itemGroup = item.join(" ");
        if (index == areaData.length - 1) {
          areaPos += itemGroup;
        } else {
          areaPos += itemGroup + ";";
        }
      });
      SpatialQuery.strPos = areaPos;
      getFeatureParams.sql = SpatialQuery;
      console.log("横断面分析this.$store.state.layersAttribute",this.$store.state.layersAttribute);
      let layersAttribute = this.$store.state.layersAttribute.filter(item => {
    if (item.includes("pipeline")) {
        console.log("横断面分析pipeline", item); // 打印符合条件的元素
        return true; // 返回 true 表示保留该元素
    }
    return false; // 不符合条件的元素不保留
});
      if (layersAttribute.length == 0) {
        this.$message.warning("请先获取服务图层");
        // this.isLoading = false;
        return;
      }
      let requestNum = 0;
      requestNum = layersAttribute.length;
      async function getFeatureByLineSon() {
        for (let item of layersAttribute) {
          console.log("横断面分析item", item);
          getFeatureParams.strlayername = item;
          try {
            await this.projectLayer
              .SendFeatureMapService(getFeatureParams)
              .then((res) => {
                if (res.objset) {
                  res.objset.map((item) => {
                    let dataObject = {};
                    item.rec.forEach((data) => {
                      console.log("rec",data)
                      dataObject[data.fldname] = data.fldval;
                      let Type=this.convertLayerNameToFormattedString(getFeatureParams.strlayername);
                      dataObject.type = Type;
                      console.log("recType",dataObject.type )
                    });
                    resultData.push(dataObject);
                    console.log("resultData",resultData);
                  });
                }
                // dmgis.olmap.ServiceLayer.prototype.HandleFeatureInfo =
                //   function (feature) {
                //     if (feature.objset) {
                //       feature.objset.map((item) => {
                //         let dataObject = {};
                //         item.rec.forEach((data) => {
                //           dataObject[data.fldname] = data.fldval;
                //           dataObject.type = getFeatureParams.strlayername;
                //         });
                //         resultData.push(dataObject);
                //       });
                //     }
                //   };
              });
          } catch (error) {
            console.error("获取图层特征时出错:", error);
          } finally {
            requestNum--;
            console.log("requestNum", requestNum);
            if (requestNum == 0) {
              this.isCrossLoading = false;
              if (resultData.length == 0) {
                this.$message.warning("未查询到数据！");
              } 
              // else if (resultData.length > 1) {
              //   this.$message.warning("查询到多条数据！");
              // }
               else {
                this.$message.success("数据获取成功");
                this.areaTableData = [resultData[0]];
              }
            }
          }
        }
      }
      getFeatureByLineSon.call(this);
      // const h = this.$createElement;
      // this.$msgbox({
      //   title: "横断面分析",
      //   message: h("p", null, [h("span", null, "是否查询该区域? ")]),
      //   showCancelButton: true,
      //   distinguishCancelAndClose: true,
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      // }).then((action) => {
      //   if (action == "confirm") {
      //   }
      // });
    },
  },
  mounted() {
    this.initMap();
    this.initLayer();
    this.$store.commit("setshowValveOperate", false);
  },
};
</script>

<style lang="scss" scoped>
//快捷定位弹窗样式
.toolDialog {
  z-index: 2;
  font-size: 0.8rem;
  //   background-color: #285383;
  color: white;
  //   padding: 10px;
  position: absolute;
  top: 100%;
  width: 165px;
  box-sizing: border-box;

  .positonBar {
    background-color: #285383;
  }
  //   .componentContainer {
  //     position: absolute;
  //     width: 50rem;
  //     height: 50rem;
  //     top: 0;
  //     left: -20rem;

  //   }
  .tool-item {
    cursor: pointer;
    display: flex;
    align-items: center;
    padding: 8px;
  }
  .tool-item:hover {
    background-color: #4998f2;
  }
  .tool-item:focus {
    background-color: #4998f2;
  }
}
</style>
